<template>
    <div class="flex-1 flex flex-col bg-[#0f0f0f] relative" :class="{ 'fullscreen-container': isFullscreen }">
        <!-- 工具栏 -->
        <div class="flex items-center justify-between px-6 py-3 bg-[#1a1a1a] border-b border-gray-700"
            :class="{ 'fullscreen-toolbar': isFullscreen }">
            <div class="flex items-center space-x-3">
                <div class="flex items-center space-x-2 text-gray-300">
                    <el-icon>
                        <Box />
                    </el-icon>
                    <span class="text-sm font-medium">3D 视窗</span>
                </div>

                <!-- 视图控制 -->
                <div class="flex items-center space-x-1 ml-6">
                    <el-button size="small"
                        :class="cameraMode === 'perspective' ? '!bg-blue-500 !text-white' : '!bg-gray-600 !text-gray-200'"
                        @click="setCameraMode('perspective')">
                        透视
                    </el-button>
                    <el-button size="small"
                        :class="cameraMode === 'orthographic' ? '!bg-blue-500 !text-white' : '!bg-gray-600 !text-gray-200'"
                        @click="setCameraMode('orthographic')">
                        正交
                    </el-button>
                </div>

                <!-- 渲染模式 -->
                <el-dropdown @command="setRenderMode">
                    <el-button size="small" class="!bg-gray-600 !text-gray-200">
                        {{ getRenderModeText() }}
                        <el-icon class="ml-1">
                            <ArrowDown />
                        </el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu class="!bg-gray-800 !border-gray-600">
                            <el-dropdown-item command="solid" class="!text-gray-200">实体</el-dropdown-item>
                            <el-dropdown-item command="wireframe" class="!text-gray-200">线框</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>

                <!-- 光照控制 -->
                <el-dropdown @command="setLightingPreset">
                    <el-button size="small" class="!bg-yellow-600 !text-gray-200">
                        {{ getLightingPresetText() }}
                        <el-icon class="ml-1">
                            <ArrowDown />
                        </el-icon>
                    </el-button>
                    <template #dropdown>
                        <el-dropdown-menu class="!bg-gray-800 !border-gray-600">
                            <el-dropdown-item command="balanced" class="!text-gray-200">平衡光照</el-dropdown-item>
                            <el-dropdown-item command="bright" class="!text-gray-200">明亮模式</el-dropdown-item>
                            <el-dropdown-item command="soft" class="!text-gray-200">柔和模式</el-dropdown-item>
                            <el-dropdown-item command="dramatic" class="!text-gray-200">戏剧性</el-dropdown-item>
                        </el-dropdown-menu>
                    </template>
                </el-dropdown>
            </div>

            <div class="flex items-center space-x-2">
                <!-- 自动旋转 -->
                <el-button size="small"
                    :class="autoRotate ? '!bg-green-500 !text-white' : '!bg-gray-600 !text-gray-200'"
                    @click="toggleAutoRotate">
                    <el-icon>
                        <Refresh />
                    </el-icon>
                </el-button>

                <!-- 重置视角 -->
                <el-button size="small" class="!bg-gray-600 !text-gray-200" @click="resetCamera">
                    <el-icon>
                        <Position />
                    </el-icon>
                    重置
                </el-button>

                <!-- 网格切换 -->
                <el-button size="small" :class="showGrid ? '!bg-blue-500 !text-white' : '!bg-gray-600 !text-gray-200'"
                    @click="toggleGrid">
                    <el-icon>
                        <Grid />
                    </el-icon>
                </el-button>

                <!-- 截图 -->
                <el-button size="small" class="!bg-purple-600 !text-white" @click="captureScreenshot"
                    :disabled="!hasModel">
                    <el-icon>
                        <Camera />
                    </el-icon>
                </el-button>

                <!-- 全屏按钮 -->
                <el-button size="small"
                    :class="isFullscreen ? '!bg-orange-500 !text-white' : '!bg-gray-600 !text-gray-200'"
                    @click="toggleFullscreen" :title="isFullscreen ? '退出全屏' : '进入全屏'">
                    <el-icon>
                        <FullScreen v-if="!isFullscreen" />
                        <Aim v-else />
                    </el-icon>
                </el-button>
            </div>
        </div>

        <!-- 画布区域 -->
        <div class="flex-1 relative" ref="canvasContainer" :class="{ 'fullscreen-canvas-container': isFullscreen }">
            <canvas ref="canvasRef" class="w-full h-full cursor-move" @contextmenu.prevent></canvas>

            <!-- 全屏时的ESC提示 -->
            <div v-if="isFullscreen && showFullscreenHint"
                class="absolute top-4 left-1/2 transform -translate-x-1/2 bg-black/80 backdrop-blur-sm rounded-lg px-4 py-2 text-white text-sm z-30">
                <div class="flex items-center space-x-2">
                    <el-icon class="text-orange-400">
                        <Warning />
                    </el-icon>
                    <span>按 ESC 键退出全屏</span>
                    <el-button size="small" text @click="hideFullscreenHint" class="!text-gray-300 ml-2">
                        ×
                    </el-button>
                </div>
            </div>

            <!-- 加载状态 -->
            <div v-if="isLoading"
                class="absolute inset-0 flex items-center justify-center bg-black/20 backdrop-blur-sm z-20">
                <div class="text-center bg-[#1a1a1a] p-8 rounded-2xl border border-gray-700">
                    <el-icon class="animate-spin text-blue-500 text-6xl mb-4">
                        <Loading />
                    </el-icon>
                    <div class="text-xl text-gray-100 mb-2">正在加载3D模型...</div>
                    <div class="text-gray-300">{{ loadingText }}</div>
                    <div class="w-64 mx-auto mt-4">
                        <el-progress :percentage="loadingProgress" :show-text="false" />
                    </div>
                </div>
            </div>

            <!-- 空状态 -->
            <div v-if="!hasModel && !isLoading" class="absolute inset-0 flex items-center justify-center">
                <div class="text-center">
                    <div
                        class="w-32 h-32 mx-auto mb-6 rounded-2xl bg-gradient-to-br from-gray-700 to-gray-800 flex items-center justify-center">
                        <el-icon class="text-6xl text-gray-500">
                            <Box />
                        </el-icon>
                    </div>
                    <h2 class="text-3xl font-bold mb-4">
                        <span class="text-blue-500">3D</span>
                        <span
                            class="bg-gradient-to-r from-orange-400 to-orange-600 bg-clip-text text-transparent">Canvas</span>
                    </h2>
                    <p class="text-gray-400 text-lg">暂无3D模型加载</p>
                    <div class="mt-6 text-sm text-gray-500">
                        监听状态: {{ eventBusStatus }}
                    </div>
                </div>
            </div>

            <!-- 错误状态 -->
            <div v-if="errorMessage"
                class="absolute inset-0 flex items-center justify-center bg-black/20 backdrop-blur-sm z-20">
                <div class="text-center bg-red-900/80 p-8 rounded-2xl border border-red-600 max-w-md">
                    <el-icon class="text-red-400 text-4xl mb-4">
                        <WarningFilled />
                    </el-icon>
                    <div class="text-xl text-red-200 mb-2">加载失败</div>
                    <div class="text-red-300 mb-4 text-sm">{{ errorMessage }}</div>
                    <el-button size="small" @click="clearError" type="danger">关闭</el-button>
                </div>
            </div>

            <!-- 模型信息 -->
            <div v-if="modelInfo"
                class="absolute top-4 left-4 bg-black/60 backdrop-blur-sm rounded-lg p-3 text-sm text-gray-200 z-10"
                :class="{ 'fullscreen-model-info': isFullscreen }">
                <div class="flex items-center space-x-4">
                    <div>{{ cameraMode === 'perspective' ? '透视' : '正交' }}</div>
                    <div>面数: {{ formatNumber(modelInfo.faces) }}</div>
                    <div>顶点: {{ formatNumber(modelInfo.vertices) }}</div>
                    <div v-if="isFullscreen" class="text-orange-400">全屏模式</div>
                </div>
            </div>

            <!-- EventBus 状态指示器 -->
            <div v-if="showEventBusStatus"
                class="absolute top-4 right-4 bg-black/60 backdrop-blur-sm rounded-lg p-2 text-xs text-gray-200 z-10">
                <div class="flex items-center space-x-2">
                    <div :class="`w-2 h-2 rounded-full ${eventBusConnected ? 'bg-green-400' : 'bg-red-400'}`"></div>
                    <span>EventBus</span>
                </div>
            </div>
        </div>

        <!-- 状态栏 -->
        <div class="px-6 py-2 bg-[#1a1a1a] border-t border-gray-700 flex items-center justify-between text-xs text-gray-300"
            :class="{ 'fullscreen-statusbar': isFullscreen }">
            <div class="flex items-center space-x-4">
                <span>WebGL 2.0</span>
                <span v-if="modelInfo">{{ modelInfo.name || '3D模型' }}</span>
                <span v-if="lastEventInfo">最后事件: {{ lastEventInfo }}</span>
                <span v-if="isFullscreen" class="text-orange-400">● 全屏模式</span>
            </div>
            <div class="flex items-center space-x-4">
                <div class="flex items-center space-x-1">
                    <div :class="`w-2 h-2 rounded-full ${getStatusColor()}`"></div>
                    <span>{{ getStatusText() }}</span>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, onUnmounted, nextTick } from 'vue'
import { Box, Refresh, Grid, Loading, Camera, ArrowDown, Position, WarningFilled, FullScreen, Aim, Warning } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { EnhancedThreeRenderer } from '@/hook/use3DRenderer'
import modelEventBus, { MODEL_EVENTS } from '@/util/eventbus/modelEventBus'

const emit = defineEmits(['model-loaded', 'model-error', 'screenshot-taken', 'fullscreen-changed'])

// ========== 引用 ==========
const canvasRef = ref(null)
const canvasContainer = ref(null)
let threeRenderer = null

// ========== 状态管理 ==========
const cameraMode = ref('perspective')
const renderMode = ref('solid')
const lightingPreset = ref('balanced')
const autoRotate = ref(false)
const showGrid = ref(true)

const isLoading = ref(false)
const loadingProgress = ref(0)
const loadingText = ref('准备加载模型...')
const errorMessage = ref(null)

const modelInfo = ref(null)
const hasModel = computed(() => !!modelInfo.value)

// ========== 全屏状态管理 ==========
const isFullscreen = ref(false)
const showFullscreenHint = ref(true)
const fullscreenElement = ref(null)

// ========== EventBus 状态监控 ==========
const eventBusConnected = ref(false)
const eventBusStatus = ref('等待连接')
const showEventBusStatus = ref(true)
const lastEventInfo = ref('')

// ========== 工具方法 ==========
const formatNumber = (num) => {
    if (!num) return '0'
    if (num >= 1000000) return (num / 1000000).toFixed(1) + 'M'
    if (num >= 1000) return (num / 1000).toFixed(1) + 'K'
    return num.toString()
}

const getRenderModeText = () => {
    return renderMode.value === 'solid' ? '实体' : '线框'
}

const getLightingPresetText = () => {
    const presets = {
        'balanced': '平衡光照',
        'bright': '明亮模式',
        'soft': '柔和模式',
        'dramatic': '戏剧性'
    }
    return presets[lightingPreset.value] || '平衡光照'
}

const getStatusColor = () => {
    if (errorMessage.value) return 'bg-red-500'
    if (isLoading.value) return 'bg-yellow-500'
    if (hasModel.value) return 'bg-green-500'
    return 'bg-gray-500'
}

const getStatusText = () => {
    if (errorMessage.value) return '错误'
    if (isLoading.value) return '加载中'
    if (hasModel.value) return '就绪'
    return '待机'
}

const hideFullscreenHint = () => {
    showFullscreenHint.value = false
}

// ========== 全屏功能 ==========
const toggleFullscreen = async () => {
    try {
        if (!isFullscreen.value) {
            await enterFullscreen()
        } else {
            await exitFullscreen()
        }
    } catch (error) {
        console.error('[Canvas] 全屏切换失败:', error)
        ElMessage.error('全屏功能不可用')
    }
}

const enterFullscreen = async () => {
    const element = canvasContainer.value
    if (!element) return

    console.log('[Canvas] 进入全屏模式')

    try {
        if (element.requestFullscreen) {
            await element.requestFullscreen()
        } else if (element.webkitRequestFullscreen) {
            await element.webkitRequestFullscreen()
        } else if (element.msRequestFullscreen) {
            await element.msRequestFullscreen()
        } else if (element.mozRequestFullScreen) {
            await element.mozRequestFullScreen()
        } else {
            throw new Error('浏览器不支持全屏API')
        }

        fullscreenElement.value = element
        isFullscreen.value = true
        showFullscreenHint.value = true

        // 延迟调整渲染器尺寸，确保DOM更新完成
        setTimeout(() => {
            adjustRendererForFullscreen()
        }, 100)

        emit('fullscreen-changed', { isFullscreen: true })
        ElMessage.success('已进入全屏模式')

    } catch (error) {
        console.error('[Canvas] 进入全屏失败:', error)
        throw error
    }
}

const exitFullscreen = async () => {
    console.log('[Canvas] 退出全屏模式')

    try {
        if (document.exitFullscreen) {
            await document.exitFullscreen()
        } else if (document.webkitExitFullscreen) {
            await document.webkitExitFullscreen()
        } else if (document.msExitFullscreen) {
            await document.msExitFullscreen()
        } else if (document.mozCancelFullScreen) {
            await document.mozCancelFullScreen()
        }

        fullscreenElement.value = null
        isFullscreen.value = false

        // 延迟调整渲染器尺寸
        setTimeout(() => {
            adjustRendererForNormalMode()
        }, 100)

        emit('fullscreen-changed', { isFullscreen: false })
        ElMessage.info('已退出全屏模式')

    } catch (error) {
        console.error('[Canvas] 退出全屏失败:', error)
        throw error
    }
}

const adjustRendererForFullscreen = () => {
    if (threeRenderer && canvasRef.value) {
        console.log('[Canvas] 调整渲染器为全屏尺寸')

        // 强制触发resize事件
        threeRenderer.onWindowResize()

        // 确保画布填满全屏
        const canvas = canvasRef.value
        const container = canvasContainer.value
        if (container) {
            canvas.style.width = '100vw'
            canvas.style.height = '100vh'
        }
    }
}

const adjustRendererForNormalMode = () => {
    if (threeRenderer && canvasRef.value) {
        console.log('[Canvas] 调整渲染器为普通尺寸')

        // 恢复正常尺寸
        const canvas = canvasRef.value
        canvas.style.width = '100%'
        canvas.style.height = '100%'

        // 触发resize事件
        threeRenderer.onWindowResize()
    }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
    const fullscreenElement = document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.msFullscreenElement ||
        document.mozFullScreenElement

    const wasFullscreen = isFullscreen.value
    isFullscreen.value = !!fullscreenElement

    console.log('[Canvas] 全屏状态变化:', { wasFullscreen, isFullscreen: isFullscreen.value })

    if (wasFullscreen && !isFullscreen.value) {
        // 从全屏退出
        setTimeout(() => {
            adjustRendererForNormalMode()
        }, 100)
        emit('fullscreen-changed', { isFullscreen: false })
    } else if (!wasFullscreen && isFullscreen.value) {
        // 进入全屏
        setTimeout(() => {
            adjustRendererForFullscreen()
        }, 100)
        emit('fullscreen-changed', { isFullscreen: true })
    }
}

// 处理ESC键退出全屏
const handleKeyDown = (event) => {
    if (event.key === 'Escape' && isFullscreen.value) {
        hideFullscreenHint()
    }

    // F11键切换全屏（可选）
    if (event.key === 'F11') {
        event.preventDefault()
        toggleFullscreen()
    }
}

// ========== 3D渲染控制 ==========
const setCameraMode = (mode) => {
    cameraMode.value = mode
    if (threeRenderer) {
        threeRenderer.setCameraMode(mode)
    }
}

const setRenderMode = (mode) => {
    renderMode.value = mode
    if (threeRenderer) {
        threeRenderer.setRenderMode(mode)
    }
}

const setLightingPreset = (preset) => {
    lightingPreset.value = preset
    if (threeRenderer) {
        threeRenderer.setLightingPreset(preset)
        ElMessage.success(`已切换到${getLightingPresetText()}`)
    }
}

const toggleAutoRotate = () => {
    autoRotate.value = !autoRotate.value
    if (threeRenderer) {
        threeRenderer.setAutoRotate(autoRotate.value)
    }
}

const toggleGrid = () => {
    showGrid.value = !showGrid.value
    if (threeRenderer) {
        threeRenderer.toggleGrid(showGrid.value)
    }
}

const resetCamera = () => {
    if (threeRenderer) {
        threeRenderer.resetCamera()
    }
}

const captureScreenshot = () => {
    if (!threeRenderer) return

    try {
        // 在全屏模式下使用更高的分辨率
        const width = isFullscreen.value ? 2560 : 1920
        const height = isFullscreen.value ? 1440 : 1080

        const dataURL = threeRenderer.captureScreenshot(width, height)
        if (dataURL) {
            const link = document.createElement('a')
            link.href = dataURL
            link.download = `3d-model-${isFullscreen.value ? 'fullscreen-' : ''}${Date.now()}.png`
            link.click()
            emit('screenshot-taken', dataURL)
            ElMessage.success(`截图已保存 ${isFullscreen.value ? '(全屏)' : ''}`)
        }
    } catch (error) {
        ElMessage.error('截图失败')
    }
}

const clearError = () => {
    errorMessage.value = null
}

// ========== 模型加载 ==========
const loadModel = async (modelData) => {
    if (!threeRenderer || !modelData?.url) {
        console.log('[Canvas] 跳过加载 - 渲染器或模型URL无效:', {
            hasRenderer: !!threeRenderer,
            hasUrl: !!modelData?.url,
            modelData
        })
        return
    }

    console.log('[Canvas] 开始加载模型:', modelData.name || modelData.url)

    isLoading.value = true
    loadingProgress.value = 0
    loadingText.value = '正在加载模型...'
    errorMessage.value = null
    modelInfo.value = null

    // 发送加载中事件
    modelEventBus.emitModelLoading({
        name: modelData.name,
        url: modelData.url,
        progress: 0
    })

    try {
        const success = await threeRenderer.loadModel(modelData.url, {
            onProgress: (progress) => {
                loadingProgress.value = progress
                loadingText.value = `加载中... ${progress.toFixed(1)}%`

                // 发送加载进度事件
                modelEventBus.emitModelLoading({
                    name: modelData.name,
                    url: modelData.url,
                    progress: progress
                })
            },
            onLoaded: (info) => {
                modelInfo.value = {
                    name: modelData.name,
                    faces: info.faces,
                    vertices: info.vertices,
                    ...info
                }
                isLoading.value = false

                // 发送加载完成事件
                modelEventBus.emitModelLoaded(modelData)

                emit('model-loaded', modelData)
                ElMessage.success('模型加载完成')
            },
            onError: (error) => {
                console.error('[Canvas] 模型加载失败:', error)
                errorMessage.value = error.message
                isLoading.value = false

                // 发送错误事件
                modelEventBus.emitModelError(error)

                emit('model-error', error)
            }
        })

    } catch (error) {
        console.error('[Canvas] 加载异常:', error)
        errorMessage.value = error.message
        isLoading.value = false

        // 发送错误事件
        modelEventBus.emitModelError(error)

        emit('model-error', error)
    }
}

// ========== 清除模型 ==========
const clearModel = () => {
    console.log('[Canvas] 清除当前模型')
    if (threeRenderer) {
        threeRenderer.clearModel()
    }
    modelInfo.value = null
    isLoading.value = false
    errorMessage.value = null
}

// ========== 初始化 ==========
const initCanvas = async () => {
    if (!canvasRef.value) return

    try {
        // 原来：threeRenderer = new SimpleThreeRenderer(canvasRef.value)
        // 修复后：
        threeRenderer = new EnhancedThreeRenderer(canvasRef.value)
        await threeRenderer.initialize()

        // 设置全屏支持
        threeRenderer.setFullscreenMode(isFullscreen.value)

        // 设置初始状态
        threeRenderer.toggleGrid(showGrid.value)
        threeRenderer.setAutoRotate(autoRotate.value)

        console.log('[Canvas] 画布初始化完成')
    } catch (error) {
        console.error('[Canvas] 初始化失败:', error)
        errorMessage.value = '画布初始化失败'
    }
}

// ========== EventBus 事件处理器 ==========
const handleModelChanged = (eventData) => {
    const { data, timestamp } = eventData
    console.log('[Canvas] 收到模型变化事件:', data)

    lastEventInfo.value = `模型变化 ${new Date(timestamp).toLocaleTimeString()}`
    eventBusStatus.value = '已连接'
    eventBusConnected.value = true

    if (data && data.url) {
        loadModel(data)
    }
}

const handleModelCleared = (eventData) => {
    const { timestamp } = eventData
    console.log('[Canvas] 收到模型清除事件')

    lastEventInfo.value = `模型清除 ${new Date(timestamp).toLocaleTimeString()}`
    clearModel()
}

const handleGenerateProgress = (eventData) => {
    const { data, timestamp } = eventData
    console.log('[Canvas] 收到生成进度事件:', data)

    lastEventInfo.value = `生成进度 ${data.progress}% ${new Date(timestamp).toLocaleTimeString()}`

    // 可以在这里显示生成进度信息
    if (data.statusText) {
        // 可以显示生成状态
    }
}

const handleModelError = (eventData) => {
    const { data, timestamp } = eventData
    console.log('[Canvas] 收到模型错误事件:', data)

    lastEventInfo.value = `错误 ${new Date(timestamp).toLocaleTimeString()}`
    errorMessage.value = data.message || '未知错误'
}

// ========== EventBus 监听器设置 ==========
const setupEventBusListeners = () => {
    const componentId = 'canvas-component'

    console.log('[Canvas] 设置 EventBus 监听器')

    // 监听模型变化事件
    modelEventBus.onModelChanged(handleModelChanged, componentId)

    // 监听模型清除事件
    modelEventBus.on(MODEL_EVENTS.MODEL_CLEARED, handleModelCleared, componentId)

    // 监听生成进度事件
    modelEventBus.on(MODEL_EVENTS.GENERATE_PROGRESS, handleGenerateProgress, componentId)

    // 监听模型错误事件
    modelEventBus.onModelError(handleModelError, componentId)

    // 监听历史记录选择事件
    modelEventBus.onHistoryItemSelected(handleModelChanged, componentId)

    // 设置连接状态
    eventBusConnected.value = true
    eventBusStatus.value = '已连接'

    console.log('[Canvas] EventBus 监听器设置完成')
}

// ========== EventBus 监听器清理 ==========
const cleanupEventBusListeners = () => {
    const componentId = 'canvas-component'

    console.log('[Canvas] 清理 EventBus 监听器')
    modelEventBus.off(componentId)

    eventBusConnected.value = false
    eventBusStatus.value = '已断开'
}

// ========== 测试方法（开发时使用） ==========
const testEventBus = () => {
    console.log('[Canvas] 测试 EventBus 连接')

    // 模拟发送测试事件
    const testModel = {
        id: 'test-' + Date.now(),
        name: '测试模型',
        url: 'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf',
        type: 'test'
    }

    modelEventBus.emitModelChanged(testModel)
}

// ========== 生命周期 ==========
onMounted(async () => {
    await nextTick()

    // 先设置 EventBus 监听器
    setupEventBusListeners()

    // 然后初始化画布
    await initCanvas()

    // 设置全屏事件监听器
    document.addEventListener('fullscreenchange', handleFullscreenChange)
    document.addEventListener('webkitfullscreenchange', handleFullscreenChange)
    document.addEventListener('mozfullscreenchange', handleFullscreenChange)
    document.addEventListener('MSFullscreenChange', handleFullscreenChange)

    // 设置键盘事件监听器
    document.addEventListener('keydown', handleKeyDown)

    // 开发环境下显示EventBus状态
    if (process.env.NODE_ENV === 'development') {
        showEventBusStatus.value = true

        // 5秒后自动隐藏状态指示器
        setTimeout(() => {
            showEventBusStatus.value = false
        }, 5000)
    }

    console.log('[Canvas] 组件挂载完成')
})

onUnmounted(() => {
    // 如果当前是全屏状态，先退出全屏
    if (isFullscreen.value) {
        exitFullscreen().catch(console.error)
    }

    // 清理 Three.js 资源
    if (threeRenderer) {
        threeRenderer.dispose()
    }

    // 清理 EventBus 监听器
    cleanupEventBusListeners()

    // 清理全屏事件监听器
    document.removeEventListener('fullscreenchange', handleFullscreenChange)
    document.removeEventListener('webkitfullscreenchange', handleFullscreenChange)
    document.removeEventListener('mozfullscreenchange', handleFullscreenChange)
    document.removeEventListener('MSFullscreenChange', handleFullscreenChange)

    // 清理键盘事件监听器
    document.removeEventListener('keydown', handleKeyDown)

    console.log('[Canvas] 组件卸载完成')
})

// ========== 开发工具方法 ==========
// 在开发环境下暴露一些调试方法
if (process.env.NODE_ENV === 'development') {
    window.canvasDebug = {
        testEventBus,
        getEventBusStats: () => modelEventBus.getEventStats(),
        loadTestModel: () => {
            const testModel = {
                id: 'debug-test',
                name: 'Debug测试模型',
                url: 'https://threejs.org/examples/models/gltf/DamagedHelmet/glTF/DamagedHelmet.gltf'
            }
            modelEventBus.emitModelChanged(testModel)
        },
        toggleFullscreen: () => toggleFullscreen(),
        getFullscreenState: () => ({
            isFullscreen: isFullscreen.value,
            fullscreenElement: document.fullscreenElement
        })
    }
}
</script>

<style scoped>
canvas {
    background: radial-gradient(ellipse at center, #1a1a1a 0%, #0f0f0f 100%);
}

/* 全屏样式 */
.fullscreen-container {
    position: fixed !important;
    top: 0 !important;
    left: 0 !important;
    width: 100vw !important;
    height: 100vh !important;
    z-index: 9999 !important;
    background: #0f0f0f !important;
}

.fullscreen-canvas-container {
    width: 100vw !important;
    height: calc(100vh - 120px) !important;
    /* 减去工具栏和状态栏高度 */
}

.fullscreen-toolbar {
    position: sticky !important;
    top: 0 !important;
    z-index: 10000 !important;
    backdrop-filter: blur(10px) !important;
}

.fullscreen-statusbar {
    position: sticky !important;
    bottom: 0 !important;
    z-index: 10000 !important;
    backdrop-filter: blur(10px) !important;
}

.fullscreen-model-info {
    font-size: 16px !important;
    padding: 12px 16px !important;
    backdrop-filter: blur(15px) !important;
}

/* Element Plus 样式覆盖 */
:deep(.el-progress-bar__outer) {
    background: #374151 !important;
    border-radius: 10px !important;
}

:deep(.el-progress-bar__inner) {
    background: linear-gradient(90deg, #3b82f6, #06b6d4) !important;
    border-radius: 10px !important;
}

/* EventBus状态指示器动画 */
.eventbus-indicator {
    transition: all 0.3s ease;
}

@keyframes pulse-green {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0.5;
    }
}

@keyframes pulse-red {

    0%,
    100% {
        opacity: 1;
    }

    50% {
        opacity: 0.3;
    }
}

.bg-green-400 {
    animation: pulse-green 2s infinite;
}

.bg-red-400 {
    animation: pulse-red 1s infinite;
}

/* 全屏时的过渡动画 */
.fullscreen-container,
.fullscreen-canvas-container {
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 全屏提示动画 */
@keyframes slideInDown {
    from {
        opacity: 0;
        transform: translate(-50%, -20px);
    }

    to {
        opacity: 1;
        transform: translate(-50%, 0);
    }
}

.fullscreen-hint {
    animation: slideInDown 0.3s ease-out;
}
</style>